package com.hcbd.tdwt.ui.xingyu.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.hcbd.tdwt.R;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.cy.translucentparent.StatusNavUtils;

import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.ui.common.dialog.BottomSelectDialog;
import com.hcbd.tdwt.util.BDToGPS;
import com.hcbd.tdwt.util.OpenLocalMapUtil;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.hcbd.tdwt.util.StringUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_app_map)
public class AppMapActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener{
    private String TAG = "AppMapActivity";
    //地图
    @ViewById(R.id.map_view)
    MapView mapView;
    //当前位置图标
    @ViewById(R.id.current_location_img)
    ImageView currentLocationImg;
    //切换图层
    @ViewById(R.id.switch_map_layer_img)
    ImageView switchMapLayerImg;
    //增加缩放级别
    @ViewById(R.id.add_level_img)
    ImageView addLevelImg;
    //减少缩放级别
    @ViewById(R.id.reduce_level_img)
    ImageView reduceLevelImg;
    //经纬度
    @ViewById(R.id.location_tv)
    TextView locationTv;
    //地址
    @ViewById(R.id.adress_tv)
    TextView adressTv;
    //地图对象的操作方法与接口
    private AMap aMap;
    //图层的相关类
    private TileOverlay mtileOverlay;
    //切换图层弹框
    private BottomSelectDialog bottomSelectDialog;
    private LatLng currentLatlng;
    //地理搜索类
    private GeocodeSearch geocodeSearch;
    //地址
    private String formatAddress;
    private SharedPreferencesUtil sp;
    private  int format;
    @AfterViews
    protected void init() {

        mapView.onCreate(savedInstanceState);

        StatusNavUtils.setStatusNavBarColor(this, getColor(R.color.deep_black), getColor(R.color.white));
        setAndroidNativeLightStatusBar(false);
        sp=new SharedPreferencesUtil(this);
        List<String> list=new ArrayList<>();
        list.add("卫星图");
        list.add("标准图");
        bottomSelectDialog=new BottomSelectDialog(this, "选择图层", list, (index, str) -> {
            if(aMap==null){
                toast("加载中,请稍等");
                return;
            }
            if("卫星图".equals(str)){
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            }else{
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            }
        });
        format=sp.getAttributeInt(Constant.LATITUDE_AND_LONGITUDE_FORMAT);

        initMap();
        initData();
    }
    public void initMap(){
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        //不显示高德地图默认文字
        aMap.showMapText(true);
        //定义一个UiSettings对象
        UiSettings mUiSettings;
        //实例化UiSettings类对象
        mUiSettings = aMap.getUiSettings();
        //是否显示指南针
        mUiSettings.setCompassEnabled(false);
        //比例尺控件是否显示
        mUiSettings.setScaleControlsEnabled(true);
        //是否显示缩放按钮
        mUiSettings.setZoomControlsEnabled(false);
        //旋转手势关闭
        mUiSettings.setRotateGesturesEnabled(false);
        //是否显示定位到当前位置
        mUiSettings.setMyLocationButtonEnabled(false);
        // 卫星地图模式
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
        //移动中心点到用户当前位置
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(GlobalParams.gpsLatitude, GlobalParams.gpsLongitude), 15));

    }
    public void initData(){
        String lon = getIntent().getStringExtra("lon");
        String lat = getIntent().getStringExtra("lat");
        if (lon == null || TextUtils.isEmpty(lon) || lat == null || TextUtils.isEmpty(lat)) {
            finish();
            return;
        }
        Log.e("lon:",lon);
        Log.e("lat:",lat);
        //地理搜索类
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));

        currentLatlng = BDToGPS.castToOtherPoint(latLng, GlobalParams.pointType);
        //移动中心点到用户当前位置
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatlng, 16));
        //添加标志点
        addMarker(currentLatlng);
        locationTv.setText(MessageFormat.format("{0}{1}  {2}{3}", latLng.longitude > 0 ? "东经：" : "西经：", StringUtil.DDtoDMS_photo(latLng.longitude), latLng.latitude > 0 ? "北纬：" : "南纬：", StringUtil.DDtoDMS_photo(latLng.latitude)));
    }
    /**
     * 调整缩放级别
     *
     * @param update
     * @param callback
     * @param animated
     */
    private void changeCamera(CameraUpdate update, AMap.CancelableCallback callback, boolean animated) {
        if(aMap==null){
            toast("加载中,请稍等");
            return;
        }
        if (animated) {
            aMap.animateCamera(update, 500, callback);
        } else {
            aMap.moveCamera(update);
        }
    }
    /**
     * 通过经纬度获取地址
     *
     * @param latLng
     */
    private void getAddressByLatlng(LatLng latLng) {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP);
        //异步查询
        geocodeSearch.getFromLocationAsyn(query);
    }
    /**
     * 添加标志
     *
     * @param latLng
     */
    private void addMarker(LatLng latLng) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        //设置Marker可拖动
        markerOptions.draggable(false);
        markerOptions.icon(BitmapDescriptorFactory.fromView(getLayoutInflater().inflate(R.layout.map_marker_trail_spot_layout, null)));
        //设置marker平贴地图效果
        markerOptions.setFlat(true);
        aMap.addMarker(markerOptions);
    }

    @Click(R.id.switch_map_layer_img)
    void switchMapLayerImg(){
        BottomSelectDialog.show(bottomSelectDialog);
    }
    @Click(R.id.reduce_level_img)
    void reduceLevelImg(){
        changeCamera(CameraUpdateFactory.zoomOut(), null, true);
    }
    @Click(R.id.add_level_img)
    void addLevelImg(){
        changeCamera(CameraUpdateFactory.zoomIn(), null, true);
    }
    @Click(R.id.adress_tv)
    void addressTV(){
//        Log.e(TAG, "addressTV: "+ OpenLocalMapUtil.isGdMapInstalled());
        if (formatAddress == null) {
            getAddressByLatlng(currentLatlng);
        }
    }
    @Click(R.id.current_location_img)
    void currentLocationImg(){
        if(aMap==null){
            toast("地图加载中!");
            return;
        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatlng, 16));
    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if(regeocodeResult==null){
            toast("无地址信息,请查看网络是否通畅！");
            return;
        }
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        formatAddress = regeocodeAddress.getFormatAddress();
        adressTv.setText(formatAddress);
        adressTv.setTextColor(getResources().getColor(R.color.colorBlackgray));
        adressTv.setBackground(null);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，
        //保存地图当前的状态
        if(mapView!=null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if(mapView!=null) {
            mapView.onDestroy();
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }
    @Click
    void headLeft(){
        finish();
    }
}
